/*
 * @Author: yangzonglong
 * @Date: 2021-05-25 14:43:54
 * @version: v1.0.0
 * @Descripttion: table
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-06 15:39:23
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Row, Col, Table, Input, message } from 'antd';
import update from 'immutability-helper';
import useQueryControlWrap from '../../hooks/useQueryControlWrap';
import { ControlMap, DataItemProps, ColumnType, TableProps } from './config';
import { CanvasItemProps } from './../../interface';

const Column = Table.Column,
  designDefData = [{ id: '1' }],
  scrollStyle = { x: 'max-content' },
  rowStyle: React.CSSProperties = {
    marginBottom: '0',
    lineHeight: '48px',
    padding: '0 4px',
    marginTop: '8px',
  };

interface RefProps {
  getData(): any;
}
export interface CompoentTableProps extends CanvasItemProps {
  tableProps: TableProps;
  title?: string;

  initialValue?: any[];
  disabled?: boolean; // 为true时 预览不允许操作
}

export default forwardRef((props: CompoentTableProps, ref: React.Ref<RefProps>) => {
  const [dataSource, setDataSource] = useState<DataItemProps[]>([]);
  const { domComplete, tableProps, title, initialValue, disabled, ...canvasProps } = props;
  if (canvasProps.isDesign) useQueryControlWrap(canvasProps.id, domComplete);

  useImperativeHandle(ref, () => ({
    getData() {
      const handleDataSource: DataItemProps[] = [];
      const requiredColumns = props.tableProps.columns.filter((item) => item.options.required);

      for (let item of dataSource) {
        const copyItem = { ...item, _isEdit: false };

        requiredColumns.forEach((column) => {
          if (!copyItem[column.dataIndex as string]) {
            copyItem[column.dataIndex as string] = column.options.initialValue;
          }
        });

        for (let k in copyItem) {
          const column = props.tableProps.columns.find((item) => item.dataIndex === k);

          // 必填项校验
          if (column?.options.required && !copyItem[k]) {
            message.warning('请完整填表格');
            return false;
          }
        }

        handleDataSource.push(copyItem);
      }

      return handleDataSource;
    },
  }));

  useEffect(() => {
    if (initialValue) setDataSource(initialValue);
  }, [initialValue]);

  const onChangeLine = (record: DataItemProps, v: any, k: string) => {
    const index = dataSource.findIndex((item) => item.id === record.id);
    setDataSource(
      update(dataSource, {
        [index]: {
          [k]: {
            $set: v,
          },
        },
      })
    );
  };

  const render = (text: string, record: DataItemProps, column: ColumnType) => {
    const dataIndex = column.dataIndex as string;

    if (!record._isEdit && !canvasProps.isDesign) return record[dataIndex];

    const options = {
      size: 'small' as any,
      value: record[dataIndex] || column.options?.initialValue,
      onChange: (e: any) => {
        if (props.isDesign) return; // 设计模式下 不处理
        onChangeLine(record, e.target ? e.target.value : e, dataIndex);
      },
      options: column.options,
    };

    const Component = ControlMap[column.type] || Input;
    return <Component {...options} />;
  };
  return (
    <div {...canvasProps} style={{ padding: '0 16px' }}>
      <Row justify="space-between" align="middle" style={rowStyle}>
        <Col>{title}</Col>
      </Row>
      <Table scroll={scrollStyle} pagination={false} dataSource={canvasProps.isDesign ? designDefData : dataSource}>
        {tableProps.showItemNo && (
          <Column ellipsis width={60} title="行号" key="itemNo" render={(text, record, index) => <span>{(index + 1) * 10}</span>} />
        )}
        {tableProps.columns?.map((item) => (
          <Column ellipsis width={item.width} title={item.title} key={item.key} render={(text, record) => render(text, record, item as ColumnType)} />
        ))}
      </Table>
    </div>
  );
});
